package com.gzxx.mongo.config;

import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.StrUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Set;

/**
 * @Description 启动时将表初始化
 * @Author pengpdx
 * @Date 2020/7/21 15:11
 */
@Component
public class MongoSchemaConfig {

    private final Logger logger = LoggerFactory.getLogger(MongoSchemaConfig.class);

    /**
     * 扫描注解@Document，用于初始化的时候新建schema
     */
    @Value("${spring.data.mongodb.package}")
    public String PACKAGE_NAME;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    MongoMappingContext mongoMappingContext;

    /**
     * 启动时止执行一次,初始化未创建schema
     */
    @PostConstruct
    public void init() {
        //Assert.notNull(PACKAGE_NAME,"spring.data.mongodb.package is null");
        if (StrUtil.isBlank(PACKAGE_NAME)){
            return;
        }
        Set<Class<?>> set = ClassUtil.scanPackage(PACKAGE_NAME);
        for (Class<?> clazz : set) {
            Document document = clazz.getAnnotation(Document.class);
            if (document == null) {
                continue;
            }
            // 创建schema
            if (!mongoTemplate.collectionExists(clazz)) {
                mongoTemplate.createCollection(clazz);
                System.out.println("创建了" + clazz.getSimpleName() + "表");
            }
        }
    }


}
